package com.zhb.cloud.mail.service.impl;

import java.io.File;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

import com.zhb.cloud.base.BaseService;
import com.zhb.cloud.core.JsonReturn;
import com.zhb.cloud.core.component.MailQueueProduce;
import com.zhb.cloud.core.component.MailUtil;
import com.zhb.cloud.core.component.RedisUtil;
import com.zhb.cloud.mail.model.Email;
import com.zhb.cloud.mail.model.EmailLog;
import com.zhb.cloud.mail.service.EmailLogService;
import com.zhb.cloud.mail.service.EmailService;
import com.zhb.cloud.utils.CacheConstant;
import com.zhb.cloud.utils.Constant;

/**
 * @ClassName: EmailServiceImpl
 * @author: zhb
 * @date: 2017年11月22日 下午9:27:06
 * @Description: 邮件发送实现类
 */
@Service
public class EmailServiceImpl extends BaseService implements EmailService {

	private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
	@Autowired
	private EmailLogService logService;// 邮件日志操作
	@Autowired
	private JavaMailSender mailSender;// 执行者
	@Autowired
	private SpringTemplateEngine templateEngine;// thymeleaf

	@Value("${spring.mail.username}")
	public String username;// 发送者

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private MailUtil mailUtil;

	@Override
	public JsonReturn sendSimpleEmail(Email mail) {
		JsonReturn jsonReturn = new JsonReturn();
		logger.info("发送邮件：{}", mail.getContent());
		try {
			// 1.发邮件
			SimpleMailMessage message = new SimpleMailMessage();
			message.setFrom(username);
			message.setTo(mail.getEmail());
			message.setSubject(mail.getSubject());
			message.setText(mail.getContent());
			mailUtil.start(mailSender, message);
			// 2.数据放入缓存
			redisUtil.set(CacheConstant.VALIDATE_CODE_PREFIX + mail.getContent(), mail.getContent(),
					Constant.VALIDATE_CODE_EXPIRE);
			// 3.添加日志
			EmailLog emailLog = new EmailLog();
			emailLog.setOpType(1);
			emailLog.setTargetEmail(mail.getEmail()[0]);
			emailLog.setCreateTime(new Date());
			emailLog.setEmail(username);
			emailLog.setDescription("发送验证码");
			logService.insert(emailLog);
			jsonReturn = this.success("发送成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
			jsonReturn = this.error("发送成功");
		}
		return jsonReturn;
	}

	/**
	 * 富文本编辑器
	 */
	@Override
	public JsonReturn sendHtml(Email mail) {
		JsonReturn jsonReturn = new JsonReturn();
		try {
			// 1.1 准备邮件
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(username);
			helper.setTo(mail.getEmail());
			helper.setSubject(mail.getSubject());
			helper.setText("<html><body><img src=\"cid:springcloud\" ></body></html>", true);
			// 1.2发送图片
			File file = ResourceUtils.getFile("classpath:static" + Constant.SF_FILE_SEPARATOR + "image"
					+ Constant.SF_FILE_SEPARATOR + "springcloud.png");
			helper.addInline("springcloud", file);
			// 1.3 发送附件
			file = ResourceUtils.getFile("classpath:static" + Constant.SF_FILE_SEPARATOR + "file"
					+ Constant.SF_FILE_SEPARATOR + "关注科帮网获取更多源码.zip");
			helper.addAttachment("科帮网", file);
			mailUtil.startHtml(mailSender, message);

			// 2.数据放入缓存
			redisUtil.set(CacheConstant.VALIDATE_CODE_PREFIX + mail.getContent(), mail.getContent(),
					Constant.VALIDATE_CODE_EXPIRE);
			// 3.添加日志
			EmailLog emailLog = new EmailLog();
			emailLog.setOpType(1);
			emailLog.setTargetEmail(mail.getEmail()[0]);
			emailLog.setCreateTime(new Date());
			emailLog.setEmail(username);
			emailLog.setDescription("发送验证码");
			logService.insert(emailLog);
			jsonReturn = this.success("发送成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonReturn;
	}

	@Override
	public JsonReturn sendThymeleaf(Email mail) {
		JsonReturn jsonReturn = new JsonReturn();
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(username);
			helper.setTo(mail.getEmail());
			helper.setSubject(mail.getSubject());
			Context context = new Context();
			context.setVariable("email", mail.getEmail());
			context.setVariable("validateCode", mail.getContent());
			String text = templateEngine.process(mail.getTemplate(), context);
			helper.setText(text, true);
			mailSender.send(message);
			// 2.数据放入缓存
			redisUtil.set(CacheConstant.VALIDATE_CODE_PREFIX + mail.getContent(), mail.getContent(),
					Constant.VALIDATE_CODE_EXPIRE);
			// 3.添加日志
			EmailLog emailLog = new EmailLog();
			emailLog.setOpType(1);
			emailLog.setTargetEmail(mail.getEmail()[0]);
			emailLog.setCreateTime(new Date());
			emailLog.setEmail(username);
			emailLog.setDescription("发送验证码");
			logService.insert(emailLog);
			jsonReturn = this.success("发送成功");
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return jsonReturn;
	}

	/**
	 * 采用mq的方式做分布式邮件发送--调用生产者放入队列
	 */
	@Override
	public JsonReturn sendQueue(Email mail) {
		try {
			MailQueueProduce.getMailQueue().produce(mail);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return this.success(null);
	}

	/**
	 * redis 队列发送
	 */
	@Override
	public JsonReturn sendRedisQueue(Email mail) {
		redisTemplate.convertAndSend("mail", mail);
		return this.success(null);
	}

}
